package org.onionframework.persistence.extend;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.onionframework.core.config.SystemConfig;
import org.onionframework.persistence.model.logic.Extendable;
import org.onionframework.persistence.model.support.ExtendComponent;
import org.springframework.beans.BeanUtils;

/**
 * 创建实体类对象的扩展对象
 * @author allan
 *
 */
public class ExtendComponentUtils {

	private static Map<String,Class<? extends ExtendComponent>> cache 
		= new HashMap<String,Class<? extends ExtendComponent>>();
	
	@SuppressWarnings("unchecked")
	public static ExtendComponent create(Class<? extends Extendable> entityType){
		String typeName = entityType.getName();
		if(typeName.indexOf("_$$_") > -1){
			typeName = typeName.substring(0,entityType.getName().indexOf("_$$_"));
		}
		
		if(cache.containsKey(typeName)){
			if(cache.get(typeName) != null)
				return BeanUtils.instantiate(cache.get(typeName));
			else
				return null;
		}
		else{
			try {
				String className = SystemConfig.Config.getString(typeName + ".ex");
				if(StringUtils.isBlank(className)){
					cache.put(typeName, null);
					return null;
				}else{
					Class<? extends ExtendComponent> clazz = (Class<? extends ExtendComponent>) Class.forName(className);
					cache.put(typeName, clazz);
					return BeanUtils.instantiate(clazz);
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
}
